package com.gaga.common.utils;

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 * @author liujia
 * @version 1.0
 * @date 2025/3/30-15:32
 */
public class ResourcesUtils {

    public static String getVideoRootPath() throws FileNotFoundException {
        return ResourceUtils.getURL("classpath:").getPath();
    }

    public static File getResourceAsFile(ResourceLoader loader, String path) throws IOException {
        Resource resource = loader.getResource("classpath:" + path);
        if (resource.exists() && resource.isFile() && resource.getFile().exists()) {
            return resource.getFile(); // IDE 环境直接返回
        } else {
            // JAR 环境生成临时文件
            try (InputStream in = resource.getInputStream()) {
                Path tempFile = Files.createTempFile("temp-resource-", path.substring(path.lastIndexOf('.')));
                Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING);
                tempFile.toFile().deleteOnExit();
                return tempFile.toFile();
            }
        }
    }

}
